const { Schema, SchemaTypes } = require('../schema');

class UserBase extends Schema {
    PropertyModelDataTemplate () {
        return {
            vip_id: { type: SchemaTypes.ObjectId, required: true },
            openid: { type: SchemaTypes.String, index: true, required: true, unique: true },
            session_key: { type: SchemaTypes.String, required: true },
            createTime: { type: SchemaTypes.Number, required: true, default: require('../../module/tool/time').getCurrentTimestamp() },

            avatar: { type: SchemaTypes.String, required: false },
            nickname: { type: SchemaTypes.String, required: false },
            score: { type: SchemaTypes.Number, required: true, default: 0 },

            phone: { type: SchemaTypes.String, required: false },
            // 用户授权的区域id
            authAreaId: { type: SchemaTypes.ObjectId, required: false },

            // 是否为专职推广员
            isPromoter: { type: SchemaTypes.Boolean, required: false, default: false }
        };
    }

    async existUser (openId) {
        return this.getModel().exists({
            openid: openId
        });
    }

    async insertUserData (openId, sessionKey, vipId, nickname) {
        return this.getDoc({
            openid: openId,
            session_key: sessionKey,
            vip_id: vipId,
            nickname
        }).save();
    }

    async updateUserData (userId, nickname, avatar) {
        return this.getModel().findByIdAndUpdate(userId, {
            nickname,
            avatar
        });
    }

    async updateSessionKey (userId, sessionKey) {
        return this.getModel().findByIdAndUpdate(userId, {
            session_key: sessionKey
        });
    }

    async updateUserPhone (userId, phone) {
        return this.getModel().findByIdAndUpdate(userId, { phone });
    }

    async getUserData (userId) {
        return this.getModel().findById(userId);
    }

    async getUserIdByOpenId (openId) {
        const userData = await this.getModel().findOne({
            openid: openId
        }).select('_id');
        return userData ? userData._id : null;
    }

    async getUserInfoByOpenId (openId) {
        return this.getModel().findOne({
            openid: openId
        });
    }
}

module.exports = UserBase;
